package org.chen.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@Slf4j
public class VideoRedisUtils {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String TASK_GROUP_KEY_PREFIX = "task_group:";
    private static final String TASK_GROUP_COMPLETED_SUFFIX = ":completed";
    private static final String TASK_GROUP_FAILED_SUFFIX = ":failed";

    private static final String VIDEO_STATUS_KEY = "video:status:";
    private static final long EXPIRE_TIME = 24 * 60 * 60; // 24小时过期
    
    public void saveVideoId(String videoId) {
        String key = VIDEO_STATUS_KEY + videoId;
        stringRedisTemplate.opsForValue().set(key, "1", EXPIRE_TIME, TimeUnit.SECONDS);
    }
    
    public Set<String> getAllPendingVideoIds() {
        Set<String> keys = stringRedisTemplate.keys(VIDEO_STATUS_KEY + "*");
        if (keys == null) return new HashSet<>();

        return keys.stream()
            .map(key -> key.replace(VIDEO_STATUS_KEY, ""))
            .collect(Collectors.toSet());
    }
    
    public void removeVideoId(String videoId) {
        String key = VIDEO_STATUS_KEY + videoId;
        stringRedisTemplate.delete(key);
    }

    /**
     * 添加任务到任务组
     */
    public void addTaskToGroup(String groupId, String taskId) {
        String key = TASK_GROUP_KEY_PREFIX + groupId;
        stringRedisTemplate.opsForSet().add(key, taskId);
        // 设置24小时过期
        stringRedisTemplate.expire(key, 24, TimeUnit.HOURS);
    }

    /**
     * 标记任务已完成
     */
    public void markTaskCompleted(String groupId, String taskId) {
        String completedKey = TASK_GROUP_KEY_PREFIX + groupId + TASK_GROUP_COMPLETED_SUFFIX;
        stringRedisTemplate.opsForSet().add(completedKey, taskId);
        stringRedisTemplate.expire(completedKey, 24, TimeUnit.HOURS);
    }

    /**
     * 标记任务失败
     */
    public void markTaskFailed(String groupId, String taskId) {
        String failedKey = TASK_GROUP_KEY_PREFIX + groupId + TASK_GROUP_FAILED_SUFFIX;
        stringRedisTemplate.opsForSet().add(failedKey, taskId);
        stringRedisTemplate.expire(failedKey, 24, TimeUnit.HOURS);
    }

    /**
     * 检查任务组是否全部完成
     */
    public boolean isTaskGroupCompleted(String groupId) {
        String groupKey = TASK_GROUP_KEY_PREFIX + groupId;
        String completedKey = groupKey + TASK_GROUP_COMPLETED_SUFFIX;

        Long totalTasks = stringRedisTemplate.opsForSet().size(groupKey);
        Long completedTasks = stringRedisTemplate.opsForSet().size(completedKey);

        return totalTasks != null && completedTasks != null && totalTasks.equals(completedTasks);
    }

    /**
     * 检查任务组是否全部结束（完成或失败）
     */
    public boolean isTaskGroupFinished(String groupId) {
        String groupKey = TASK_GROUP_KEY_PREFIX + groupId;
        String completedKey = groupKey + TASK_GROUP_COMPLETED_SUFFIX;
        String failedKey = groupKey + TASK_GROUP_FAILED_SUFFIX;

        Long totalTasks = stringRedisTemplate.opsForSet().size(groupKey);
        Long completedTasks = stringRedisTemplate.opsForSet().size(completedKey);
        Long failedTasks = stringRedisTemplate.opsForSet().size(failedKey);

        return totalTasks != null && completedTasks != null && failedTasks != null &&
                totalTasks.equals(completedTasks + failedTasks);
    }

    /**
     * 检查任务组是否有已完成的任务
     */
    public boolean hasCompletedTask(String groupId) {
        String completedKey = TASK_GROUP_KEY_PREFIX + groupId + TASK_GROUP_COMPLETED_SUFFIX;
        Long completedTasks = stringRedisTemplate.opsForSet().size(completedKey);
        return completedTasks != null && completedTasks > 0;
    }

    /**
     * 清除任务的完成/失败状态
     */
    public void clearTaskStatus(String groupId, String taskId) {
        String completedKey = TASK_GROUP_KEY_PREFIX + groupId + TASK_GROUP_COMPLETED_SUFFIX;
        String failedKey = TASK_GROUP_KEY_PREFIX + groupId + TASK_GROUP_FAILED_SUFFIX;

        // 从完成和失败集合中移除任务
        stringRedisTemplate.opsForSet().remove(completedKey, taskId);
        stringRedisTemplate.opsForSet().remove(failedKey, taskId);
    }
}